package me.leiusual.sharing.util.extension

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import okio.Okio
import timber.log.Timber
import java.io.File

/**
 * Create by leiusual on 2018/7/26
 */

fun File.compressIdCard(reqWidth: Int = 512, reqHeight: Int = 512): File? {
  val options = BitmapFactory.Options()
  options.inJustDecodeBounds = true
  BitmapFactory.decodeFile(path, options)

  val width = options.outWidth
  val height = options.outHeight
  Timber.v("original bitmap size = %sx%s", width, height)

  var inSampleSize = 1
  if (height > reqWidth || width > reqHeight) {
    val halfWidth = width / 2
    val halfHeight = height / 2
    while ((halfWidth / inSampleSize) >= reqWidth && (halfHeight / inSampleSize) >= reqHeight) {
      inSampleSize *= 2
    }
  }
  Timber.v("inSampleSize = %s", inSampleSize)
  options.inSampleSize = inSampleSize
  options.inJustDecodeBounds = false

  val bitmap = BitmapFactory.decodeFile(path, options)
  Timber.v("new bitmap size = %sx%s", bitmap.width, bitmap.height)
  val file = File(path.replace(name, "small_$name"))
  Okio.buffer(Okio.sink(file)).use {
    bitmap.compress(Bitmap.CompressFormat.PNG, 60, it.outputStream())
  }
  Timber.v("new file = %s", file)
  return file
}